import { getDetailLocation, operateOnTreeLevel, returnElement } from "@/utils";
import "./index.scss";
import { useRef } from "react";
import TreeItem from "./components/TreeItem";
import { currentHandleState, currentHandleActions } from "@/store";
import { useSnapshot } from "valtio";
import { treeData } from "@/type";

const Render = (props: { clearLocation: () => void }) => {
  const { clearLocation } = props;
  const {
    domTreeData,
    currentAddComponentLocation,
    currentAddComponentIsLeft,
  } = useSnapshot(currentHandleState);
  const {
    setDomTreeData,
    setCurrentAddComponentLocation,
    setCurrentAddComponentIsLeft,
  } = currentHandleActions;

  const dragOver = (e: React.DragEvent<HTMLDivElement>) => {
    const element = getDetailLocation(
      document.elementFromPoint(e?.clientX || 0, e?.clientY || 0) as HTMLElement
    );
    const { target } = element as { target: HTMLElement };
    const mousePosition = e?.clientX;
    const domPosition = target?.getBoundingClientRect()?.left;
    const domWidth = target?.clientWidth;

    const isLeft = mousePosition - domPosition < domWidth / 2;
    setCurrentAddComponentIsLeft(isLeft);
    let locationAndKey = element;
    if (locationAndKey === "end") {
      locationAndKey = {
        location: "1",
        key: domTreeData.children[domTreeData.children.length - 1]?.key || "",
      };
    }
    if (typeof locationAndKey === "object") {
      delete locationAndKey.target;
      if (
        typeof currentAddComponentLocation === "object" &&
        locationAndKey?.location === currentAddComponentLocation?.location &&
        locationAndKey?.key === currentAddComponentLocation?.key
      ) {
        locationAndKey = "";
      }
    }

    setCurrentAddComponentLocation(locationAndKey);

    e.preventDefault();
    e.stopPropagation();
  };
  const drag = (e: React.DragEvent<HTMLDivElement>) => {
    const dom = {
      element: "Button",
      show: true,
      key: new Date().getTime().toString(),
      props: {
        "data-location": "00",
      },
      text: "测试",
      children: [],
    };

    if (!currentAddComponentLocation) return;
    console.log("将 dom 添加到 domTreeData 中", currentAddComponentLocation);

    if (currentAddComponentLocation === "start") {
      setDomTreeData({
        ...domTreeData,
        children: [dom, ...domTreeData.children],
      } as unknown as treeData.treeDataType);
    } else if (currentAddComponentLocation) {
      const da = operateOnTreeLevel(
        domTreeData,
        currentAddComponentLocation.location,
        currentAddComponentLocation.key || "",
        (node: unknown) => {
          return currentAddComponentIsLeft ? [dom, node] : [node, dom];
        }
      );
      console.log(da);
      setDomTreeData(da);
    }
    clearLocation();
    e.stopPropagation();
    e.preventDefault();
  };
  const mainRef = useRef<HTMLDivElement>(null);

  return (
    <div onDragOver={dragOver} onDrop={drag} id="main">
      <div className="render-container" key="main" ref={mainRef}>
        {returnElement(domTreeData as treeData.treeDataType)}
      </div>
      <div className="render-tree-container">
        <div
          className={`render-tree-title ${
            currentAddComponentLocation === "start"
              ? "addComponentLocation"
              : ""
          }`}
        >
          Page
        </div>
        <TreeItem
          treeData={domTreeData.children as treeData.treeDataType["children"]}
        />
      </div>
    </div>
  );
};

export default Render;
